package com.ganmiao.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(Config.class)
@Slf4j
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    RedissonClient redissonClient() {
        Config config = new Config();
        String url = "redis://" + host + ":" + port;
        SingleServerConfig serverConfig = config.useSingleServer().setAddress(url).setPassword(password).setDatabase(0);
        if (StringUtils.isNotBlank(password)) {
            serverConfig.setPassword(password);
        }
        log.info(String.format("Redisson config:[%s]", JSON.toJSONString(serverConfig)));
        return Redisson.create(config);

    }

}
